package com.it.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.it.gmall.common.result.Result;
import com.it.gmall.model.payment.PaymentInfo;
import com.it.gmall.payment.config.AlipayConfig;
import com.it.gmall.payment.service.AlipayService;
import com.it.gmall.payment.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/api/payment")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PayService payService;


    // {http://api.gmall.com/api/payment/alipay/submit/{orderId}
    // 支付宝直接返回一个页面
    // 点击支付宝支付之后 支付宝返回一个页面 弹出二维码
    @GetMapping("/alipay/submit/{orderId}")
    @ResponseBody
    public String submitPay(@PathVariable Long orderId){
        return alipayService.submitPay(orderId);
    }

    // 同步回调
    @GetMapping("/alipay/callback/return")
    public String callbackReturn(){
        return "redirect:"+ AlipayConfig.return_order_url;
    }

    // 异步回调 支付宝通知我们
    /*1.验签 使用支付宝提供的接口
    * 2.再次校验金额是否正确*/
    @PostMapping("/alipay/callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String,String> notifyMap){
        System.out.println(notifyMap);
        try {
            Boolean signVerified = AlipaySignature.rsaCheckV1(
                    notifyMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
            if(signVerified){
                // 验签成功后的后续操作
                // 判断交易是否成功
                String trade_status = notifyMap.get("trade_status");
                if("TRADE_SUCCESS".equals(trade_status)){ // 交易成功
                    // 验证总金额
                    // 支付宝返回给我们的
                    String total_amount = notifyMap.get("total_amount");
                    // 数据库保存的实际总金额
                    PaymentInfo paymentInfo = alipayService.getPaymentInfo(notifyMap.get("out_trade_no"));
                    if(paymentInfo!=null && paymentInfo.getTotalAmount().toString().equals(total_amount)){
                        System.out.println("支付成功，支付验签成功，success");

                        // 修改信息到支付表中
                        // 回调时间 回调信息 支付流水号
                        payService.updatePaymentInfo(notifyMap);

                        return "success";
                    }else{
                        System.out.println("金额错误");
                        return "fail";
                    }
                }
            }else{
                System.out.println("fail");
                return "fail";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /*total_amount=2.00
    &buyer_id=20****7
    &body=大乐透2.1
    &trade_no=2016071921001003030200089909
    &refund_fee=0.00
    &notify_time=2016-07-19 14:10:49
    &subject=大乐透2.1
    &sign_type=RSA2
    &charset=utf-8
    &notify_type=trade_status_sync
    &out_trade_no=0719141034-6418
    &gmt_close=2016-07-19 14:10:46
    &gmt_payment=2016-07-19 14:10:47
    &trade_status=TRADE_SUCCESS
    &version=1.0
    &sign=kPbQIjX+xQc8F0/A6/AocELIjhhZnGbcBN6G4MM/HmfWL4ZiHM6fWl5NQhzXJusaklZ1LFuMo+lHQUELAYeugH8LYFvxnNajOvZhuxNFbN2LhF0l/KL8ANtj8oyPM4NN7Qft2kWJTDJUpQOzCzNnV9hDxh5AaT9FPqRS6ZKxnzM=
    &gmt_create=2016-07-19 14:10:44
    &app_id=20151*****3
    &seller_id=20881021****8
    &notify_id=4a91b7a78a503640467525113fb7d8bg8e*/

    // 退款 http://payment.gmall.com/api/payment/alipay/refund/ATGUIGU158348294514133
    // 统一收单交易退款接口
    @GetMapping("alipay/refund/{outTradeNo}")
    @ResponseBody
    public Result alipayRefund(@PathVariable String outTradeNo){
        String result = alipayService.alipayRefund(outTradeNo);
        if("success".equals(result)){
            return Result.ok();
        }
        return Result.fail();
    }

    // 关闭交易接口
    @GetMapping("alipay/tradeClose")
    @ResponseBody
    public String alipayTradeClose(long orderId){
        return alipayService.alipayTradeClose(orderId);
    }
}
